package com.goldplusgold.tradedelay.app.trade.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.account.manager.AppCacheSharedPreferences;
import com.goldplusgold.support.lib.base.BaseWebViewClient;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.base.constant.IntentConstant;
import com.goldplusgold.support.lib.utils.AppInstallUtil;
import com.goldplusgold.support.lib.hybird.WebViewFragment;
import com.goldplusgold.tradedelay.app.main.activity.TDMainActivity;
import com.goldplusgold.tradedelay.app.my.activity.UserActivity;
import com.goldplusgold.tradedelay.app.my.networkservice.MyService;

/**
 * Created by admin on 2017/5/15.
 */

public class TradeWebViewFragment extends WebViewFragment implements View.OnLayoutChangeListener {
    private int mType;
    public static final int MY_PERMISSION_REQUEST_CALL_PHONE = 20;
    public String mUrl;
    //屏幕高度
    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;

    public static TradeWebViewFragment newInstance(String url, int type) {

        Bundle args = new Bundle();
        args.putString("url", url);
        args.putInt("type", type);
        TradeWebViewFragment fragment = new TradeWebViewFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        //获取屏幕高度
        if (getActivity() != null && !getActivity().isFinishing()) {
            screenHeight = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        }
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight / 3;
        mView.addOnLayoutChangeListener(this);
        super.onViewCreated(view, savedInstanceState);
    }

    RelativeLayout rootView;

    @Override
    public void init(View view) {
        super.init(view);
        //添加透明title

        Bundle args = getArguments();
        if (args != null && !args.isEmpty()) {
            mType = args.getInt("type");
            mUrl = args.getString("url");
            if (mType == 1) {
                mTitleView.getBackView().setVisibility(View.GONE);
                if (TextUtils.equals(mUrl, com.goldplusgold.tradedelay.app.trade.networkservice.ApiConfig.TRADE_LOGIN)) {
                    mTitleView.setVisibility(View.GONE);
                    displayTitle(view);
                }
            }
        }
        mWebView.setWebViewClient(new MyWebViewClient(mWebView));
        mWebView.addJavascriptInterface(new JavaScriptInterface(getActivity()), "android");
        setCookie();
    }


    private void displayTitle(View view) {
        RelativeLayout rootView = (RelativeLayout) view.findViewById(R.id.root);
        TextView titleView = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.title_layout, rootView, false);
        int height = getResources().getDimensionPixelOffset(R.dimen.title_height);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, height);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        rootView.addView(titleView, layoutParams);
    }


    private void setCookie() {
        CookieSyncManager.createInstance(getActivity());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();

        cookieManager.setCookie(mUrl, "td-access-token=" + MyService.getInstance().getToken()); // 你想设置的参数
        cookieManager.setCookie(mUrl, "_platform=android"); // 你想设置的参数
        CookieSyncManager.getInstance().sync();
    }

    @Override
    public void onResume() {
        super.onResume();
        CookieSyncManager.getInstance().startSync();
    }

    @Override
    public void onPause() {
        super.onPause();
        CookieSyncManager.getInstance().stopSync();
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
            //Log.e("lf","键盘弹起");
            if (getActivity() != null && getActivity() instanceof TDMainActivity) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        ((TDMainActivity) getActivity()).mTabMenu.setVisibility(View.GONE);
                    }
                }, 10);
                //((TDMainActivity) getActivity()).mTabMenu.setVisibility(View.GONE);
            }
        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
            //Log.e("lf","键盘关闭");
            showTdMainActivityTabView();
        }
    }

    private void showTdMainActivityTabView() {
        if (getActivity() != null && getActivity() instanceof TDMainActivity) {
            ((TDMainActivity) getActivity()).mTabMenu.setVisibility(View.VISIBLE);
        }
    }


    class MyWebViewClient extends BaseWebViewClient {

        public MyWebViewClient(WebView webView) {
            super(webView);
            registerHandler("downloadApp", new WVJBHandler() {
                @Override
                public void request(Object data, WVJBResponseCallback callback) {
                    if (AppInstallUtil.isAppAvilible(getContext())) {
                        Intent intent = new Intent();
                        intent.setClassName(AppInstallUtil.APP_PACKAGE, "com.ylink.MGessTraderYlink.activity.InitScreenActivity");
                        startActivity(intent);
                    } else {

                        String downloadUrl = "http://dx.hjtzgx.com.cn:11180/GuangxiWebsite/download/apps/GuangxiGold.apk";
                        Uri uri = Uri.parse(downloadUrl);
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);
                    }
                }
            });

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("tel:")) {
                //check if permissions are granted
                if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

                    requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSION_REQUEST_CALL_PHONE);
                } else {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "0571-56663666"));

                    startActivity(intent);
                }
                view.loadUrl(url);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mTitleView.getTitletextView().setText(view.getTitle());
            if (mWebView.canGoBack()) {
                mTitleView.getBackView().setVisibility(View.VISIBLE);
                mTitleView.getBackView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mWebView.goBack();
                    }
                });
            } else {
                //mTitleView.getBackView().setVisibility(View.GONE);
            }
        }


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == MY_PERMISSION_REQUEST_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "0571-56663666"));
                startActivity(intent);
            } else {
                // Permission Denied
                Toast.makeText(getContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    public class JavaScriptInterface {
        Context mContext;

        JavaScriptInterface(Context c) {
            mContext = c;
        }

        @JavascriptInterface
        public void tdLoginSuccess() {
            if (mType == 1) {
                getFragmentManager().beginTransaction().replace(R.id.trade_layout, TradeFragment.newInstance()).commit();
            } else {
                if (isAvailableActivity()) {
                    getActivity().finish();
                }
            }
        }

        @JavascriptInterface
        public void signOutGoldExpertAndroid() {
            MyService.getInstance().cleanToken();
            AppCacheSharedPreferences.clearUserInfo();
            Intent intent = new Intent(getActivity(), UserActivity.class);
            intent.putExtra(IntentConstant._TYPE, "h5");
            startActivity(intent);
            if (mType != 1) {
                finishActivity();
            }
        }


        @JavascriptInterface
        public void getSwitchTabTitle(String title) {
            mTitleView.getTitletextView().setText(title);
        }

        @JavascriptInterface
        public void downloadApp() {
            if (AppInstallUtil.isAppAvilible(getContext())) {
                Intent intent = new Intent();
                intent.setClassName(AppInstallUtil.APP_PACKAGE, "com.ylink.MGessTraderYlink.activity.InitScreenActivity");
                startActivity(intent);
            } else {
                String downloadUrl = "http://dx.hjtzgx.com.cn:11180/GuangxiWebsite/download/apps/GuangxiGold.apk";
                Uri uri = Uri.parse(downloadUrl);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


}
